using System;
using System.Collections;
using System.Collections.Generic;

namespace PaulRz.Util
{
	/// <summary>
	/// Summary description for LogBuffer.
	/// Methods Enqueue and ToStringArray are thread-safe, all others aren't.
	/// </summary>
	public class LogBuffer : Queue<string>
	{
		// in NET 1.1 we can't obtain the memory allocated by object
		// so we'll trim logrecords enqueued
		private readonly int MAX_LOG_RECORD_LENGTH = 10000; // about 10k
		
		public LogBuffer(int length) 
		{
			this.length = length;
		}

		public LogBuffer()
		{
	
		}
		
		private int length;

		public int Length
		{
			get { return length; }
			set { length = value; }
		}

		public static void test()
		{
			LogBuffer lb=new LogBuffer(200);
			for(int i=0;i<50000;i++)
			{
				lb.Enqueue("aslkdfh adfhs ldkfjh skj dfhskjhdfjkh askdj faskdfjasdfhs");
				Console.Out.WriteLine(lb.Count+" "+i);
			}
		}

		public new void Enqueue(string obj)
		{
			string logRecord = FUtil.arrangeLogRecord(obj.ToString());
			// trim logRecord for max_size
			if (logRecord.Length > MAX_LOG_RECORD_LENGTH)
				logRecord = logRecord.Substring(0, MAX_LOG_RECORD_LENGTH);
			
			lock(this)
			{
				while(Count>length)
				{
					Dequeue();
				}
				base.Enqueue(logRecord);
			}
		}
	    
		public string[] ToStringArray()
		{
			lock(this)
			{
                return (new List<string>(this)).ToArray();
			}
		}
	}
}
